package com.tools.demo.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;
import com.tools.demo.config.MiniConfig;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.*;

/**
 * @author xinyuquan
 * @date 2019 01 2019/1/4 10:17 AM
 */
@Slf4j
@RestController
@PropertySource("classpath:application-wechat.yml")
public class IndexController {

    private final MiniConfig miniConfig;
    @Value("${wechat.miniapp.appid}")
    public String appId;
    private Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Autowired
    public IndexController(MiniConfig miniConfig) {
        this.miniConfig = miniConfig;
    }

    @GetMapping(value = "/minimsg", produces = "application/xml;charset=UTF-8")
    public String msg(
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce
    ) {
        WxMaService wxMaService = new WxMaServiceImpl();
        WxMaInMemoryConfig wxMaConfig = new WxMaInMemoryConfig();
        wxMaConfig.setAesKey(miniConfig.getAeskey());
        wxMaConfig.setAppid(miniConfig.getAppid());
        wxMaConfig.setToken(miniConfig.getToken());
        wxMaConfig.setSecret(miniConfig.getSecret());
        wxMaService.setWxMaConfig(wxMaConfig);
        Boolean checkRes = wxMaService.checkSignature(timestamp, nonce, signature);
        if (!checkRes) {
            logger.error("校验微信签名失败");
            return "";
        }
        return "success";
    }
}
